package com.roc.rocketmqconsumer.messageType;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeOrderlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeOrderlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerOrderly;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;

import java.util.List;

public class OrderMsgConsumer {
    public static void main(String[] args) throws Exception {
        // 实例化消费者，指定消费者组名
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("roc_consumer_group");
        // 设置 NameServer 地址
        consumer.setNamesrvAddr("127.0.0.1:9876");
        // 订阅 Topic 和 Tag
        // 设置从第一个位置开始消费
        consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);

        // 订阅Topic和Tag
        consumer.subscribe("TOPIC_ORDER", "TagA || TagB || TagC || TagD || TagE");

        // 注册顺序消息监听器
        consumer.registerMessageListener(new MessageListenerOrderly() {
            @Override
            public ConsumeOrderlyStatus consumeMessage(List<MessageExt> msgs, ConsumeOrderlyContext context) {
                context.setAutoCommit(true);
                // 遍历消息
                for (MessageExt msg : msgs) {
                    // 打印消息内容
                    System.out.printf("Thread: %s, QueueId: %s, OrderId: %s, Content: %s%n",
                            Thread.currentThread().getName(),
                            msg.getQueueId(),
                            msg.getKeys(),
                            new String(msg.getBody()));
                }
                return ConsumeOrderlyStatus.SUCCESS;
            }
        });

        // 启动消费者
        consumer.start();
        System.err.println("顺序消息消费者已启动……");
    }
}